package org.jeecg.modules.simulator.factory;

import lombok.Setter;

import org.jeecg.modules.simulator.factory.train.plan.TimePlanFactory;
import org.jeecg.modules.simulator.factory.train.plan.TimePlanJsonFactory;
import org.jeecg.modules.simulator.factory.train.plan.Train2Parker;
import org.jeecg.modules.simulator.jsonot.*;

import org.jeecg.modules.simulator.model.SceneDataType;
import org.jeecg.modules.simulator.model.SimulatorParam;
import org.jeecg.modules.simulator.model.line.station.station.Station;
import org.jeecg.modules.simulator.model.line.station.station.TransferStation;
import org.jeecg.modules.simulator.model.person.Person;
import org.jeecg.modules.simulator.model.person.path.PersonPath;

import lombok.Getter;
import org.jeecg.modules.simulator.model.train.timeplan.TrainPlanTable;
import org.jeecg.modules.simulator.service.HistoryBizPersonLoaderService;
import org.jeecg.modules.simulator.service.HistoryBizTrainLoaderService;
import org.jeecg.modules.simulator.service.T80RouteHisService;
import org.jeecg.modules.simulator.util.UnitCache;
import org.jeecg.modules.simulator.vo.VirtualTrainSchedularQueryCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @program: gp2
 * @description:
 * @author: renzhg
 * @create: 2024-08-29 10:55
 **/
@Component
public class DataBizFactory {

    @Setter
    String sceneCode;

//    @Setter
//    SimulatorParam simulatorParam;

    TimePlanFactory timePlanFactory = new TimePlanJsonFactory();
    PersonPathFactory personPathFactory = new PersonPathJsonFactory();

    //    @Getter
//    private Map<String, Line> lineMap = new HashMap<>();
//    @Getter
//    private Map<String, List<Station>> stationMap = new HashMap<>();//按线路分类
//    @Getter
//    private Map<String, TransferStation> transferStationMap = new HashMap<>();
//    @Getter
//    private Map<String, List<Parker>> parkerMap = new HashMap<>();//按线路分类
//    @Getter
//    Map<String, TrainPhysics> trainPhysicsMap = new HashMap<>();
//    @Getter
//    Map<String, List<OrbitPoint>> orbitPointpMap = new HashMap<>();


    @Setter
    @Getter
    Map<String, TransferStation> transferStationMap = new HashMap<>();
    @Setter
    @Getter
    public Map<String, Station> stationMap = new HashMap<>();
    @Getter
    Map<String, PersonPath> personPathMap = new HashMap<>();//key=路径序号+首站名称
    @Getter
    Map<String, List<TrainPlanTable>> trainPlanTableMapByLine = new HashMap<>();
    @Getter
    List<Train2Parker> tplist = new ArrayList<>();

    //各站人员OD分配概率,key:定义odID
    @Getter
    @Setter
    Map<String, List<ODProbabilityApiInfo>> odProbabilityApiInfoMap = new HashMap<>();


//    乘车人员分布,key:定义odID

    @Getter
    @Setter
    Map<String, TrainPsgDistributionApiInfo> trainPsgDistributionApiInfoMap = new HashMap<>();
    @Getter
    @Setter
    Map<String, Map<String, NumPeopEnStationApiInfo>> numPeopEnStationApiInfoMap = new HashMap<>();
    //    车站人员分布, key:stationId,这个只是路径信息，不是人员信息
    @Getter
    @Setter
    Map<String, List<PsgStationDistributionInfo>> psgStationDistributionInfoMap = new HashMap<>();
    //乘车人员分布
    @Getter
    Map<String, List<Person>> personTrainMap = new HashMap<>();
    @Getter
    //key:列车id，第二个key：阶段路线起始站（可以是换乘站或者开始站）-下车车站名
    Map<String, Map<String, List<Person>>> personTrainMapByLine = new HashMap<>();

    /**
     * @description: 加载列车相关数据包括列车类型数据和列车时刻表数据
     * @author: renzhg
     * @date: 2024/8/30 13:54
     **/

//    @Getter
//    Map<String, List<MetroTrain>> noAssignMetroTrainMap = new HashMap<>();
    public void loadBiz(LoadHistoryData loadTimePeriodHistory) {
//// 使用场景代码获取模拟器参数
//        SimulatorParam simulatorParam = UnitCache.simulatorParamMap.get(sceneCode);
//        // 加载列车时刻表
//        loadTrain(loadTimePeriodHistory);//列车时刻表加载
//        //   加载车辆数量及类型数据
//        loadTimePeriodHistory.loadHistoryPerson(stationMap, transferStationMap, sceneCode);
//        loadHistoryBiz(loadTimePeriodHistory);
//        // 初始化一个映射，用于存储按线路分类的列车计划表
//        //过滤不需要的分类
//        Map<String, List<TrainPlanTable>> trainPlanTableMap = new HashMap<>();
//        trainPlanTableMapByLine.forEach((lineId, trainPlanTables) -> {
//            Map<String, List<TrainPlanTable>> trainPlMap = trainPlanTables.stream().collect(Collectors.groupingBy(e -> e.getTrainId() + e.getTrainNum()));
//            if (simulatorParam.getShowLines().contains(lineId)) {
//                trainPlanTableMap.putAll(trainPlMap);
//            }
////            trainPlanTableMap.putAll(trainPlMap);
//        });
//
//
//        String compareTime = UnitCache.sceneParamMap.get(sceneCode).getStartTime().toString();
//        calculatePersonPath2Person(trainPlanTableMap, compareTime);

    }


    public void loadTrainBizData(LoadHistoryTrainData loadTrainPeriodHistory){

        // 使用场景代码获取模拟器参数
        SimulatorParam simulatorParam = UnitCache.simulatorParamMap.get(sceneCode);
        // 加载列车时刻表
        loadTrainPeriodHistory.loadHistroyTrain(stationMap, transferStationMap, sceneCode);
        trainPlanTableMapByLine = loadTrainPeriodHistory.getTrainPlanTableMapByLine();
//        Map<String, List<TrainPlanTable>> trainPlanTableMap = new HashMap<>();
//        trainPlanTableMapByLine.forEach((lineId, trainPlanTables) -> {
//            Map<String, List<TrainPlanTable>> trainPlMap = trainPlanTables.stream().collect(Collectors.groupingBy(e -> e.getTrainId() + e.getTrainNum()));
//            if (simulatorParam.getShowLines().contains(lineId)) {
//                trainPlanTableMap.putAll(trainPlMap);
//            }
//        });




//        loadTrain(loadTimePeriodHistory);//列车时刻表加载
    }

    private void calculatePersonPath2Person(Map<String, List<TrainPlanTable>> trainPlanTableMap, String compareTime) {
        personTrainMap.forEach((odId, personList) -> {
            List<TrainPlanTable> trainPlanTableList = trainPlanTableMap.get(odId);
            Collections.sort(trainPlanTableList);
            Map<String, List<Person>> personMap = new HashMap<>();
            List<String> stationsInTimeRange = findStationsInTimeRange(trainPlanTableList, compareTime);
            if (!stationsInTimeRange.isEmpty()) {
                personList.forEach(person -> {
                    PersonPath personPath = person.getPersonPath();
                    String nodeStr = personPath.getNodeStr(stationsInTimeRange.get(0));
                    if (!nodeStr.isEmpty()) {
                        if (personMap.containsKey(nodeStr)) {
                            personMap.get(nodeStr).add(person);
                        } else {
                            List<Person> personList1 = new ArrayList<>();
                            personList1.add(person);
                            personMap.put(nodeStr, personList1);
                        }

                    }

                });
            }


            personTrainMapByLine.put(odId, personMap);


        });
    }

    public List<String> findStationsInTimeRange(List<TrainPlanTable> trainPlanTableList, String timePoint) {
        List<String> result = new ArrayList<>();

        TrainPlanTable previousTrain = null;
        TrainPlanTable nextTrain = null;

        for (TrainPlanTable train : trainPlanTableList) {
            // 比较 departTime 和 arriveTime 与 timePoint 的关系
            if (train.getDepartTime().compareTo(timePoint) < 0) { // departTime 在时间点之前
                previousTrain = train;
            }
            if (train.getArriveTime().compareTo(timePoint) > 0) { // arriveTime 在时间点之后
                nextTrain = train;
                break; // 找到下一个满足条件的火车后退出循环
            }
        }

        // 如果找到符合条件的火车
        if (previousTrain != null && nextTrain != null) {
            result.add(previousTrain.getArriveStaionName());
        }

        return result;
    }

    //判断是否加载历史数据
    //如果加载历史数据，则调用加载
    //列车数据如下
    // 1、列车时刻表
    //2、列车数量数据部署位置

    //人员数据入下：
    //1、各站人员OD分配概率
    //2、站内人员分布
    //3、乘车人员分布
    //4、一个时间段内每秒刷卡进站人数
    public void loadHistoryBiz(LoadHistoryData loadTimePeriodHistory) {
////        loadHistoryPersonPathBiz();
////        LoadHistoryData loadTimePeriodHistoryPerson = new LoadTimePeriodHistory();
//        psgStationDistributionInfoMap = loadTimePeriodHistory.getPsgStationDistributionInfoMap();
//        numPeopEnStationApiInfoMap = loadTimePeriodHistory.getNumPeopEnStationApiInfoMap();

    }


//    public void loadHistoryPersonPathBiz() {
//        loadT80Route();//人员路径表
//
//        historyBizPersonLoaderService.setStationMap(stationMap);
//        historyBizPersonLoaderService.setTransferStationMap(transferStationMap);
//        PsgStationDistributionInfo psgStationDistributionInfo = new PsgStationDistributionInfo();
//        loadODAssignPerson();
//
//        historyBizPersonLoaderService.getPsgStationDistribution("2024-09-28 08:13:00");
//        //2、站内人员分布
//        psgStationDistributionInfoMap = historyBizPersonLoaderService.getStationPersonMap();
//
////        3、乘车人员分布
//        historyBizPersonLoaderService.getTrainPsgStationDistribution("2024-09-28 08:13:00");
//        personTrainMap = historyBizPersonLoaderService.getPersonTrainMap();
//
//        loadEntryStationNum();
//
//
//    }





    //加载车辆数量及类型数据
    private void loadTrain(LoadHistoryData loadTimePeriodHistory) {
//        SceneDataType sceneDataType= UnitCache.sceneParamMap.get(sceneCode).getSceneType();
//        if (sceneDataType.equals(SceneDataType.customJson)) {
//            timePlanFactory.loadTimePlanData();
//            trainPlanTableMapByLine = timePlanFactory.getTrainPlanTableByLineMap();
//        } else {
//
//        loadTimePeriodHistory.loadHistroyTrain(stationMap, transferStationMap, sceneCode);
//        trainPlanTableMapByLine = loadTimePeriodHistory.getTrainPlanTableMapByLine();

//        }
    }


}
